<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>任务管理 - Bou Scheduler</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="bi bi-clock-history"></i> Bou Scheduler
            </a>
            <div class="collapse navbar-collapse">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/tasks">任务管理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/monitor">监控统计</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/settings">系统设置</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <div class="container mt-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1><i class="bi bi-list-task"></i> 任务管理</h1>
            <div class="btn-group" role="group">
                <button class="btn btn-primary" onclick="showCreateModal()">
                    <i class="bi bi-plus-circle"></i> 创建任务
                </button>
                <button class="btn btn-warning" onclick="cleanupCompletedTasks()">
                    <i class="bi bi-trash"></i> 清理已完成任务
                </button>
                <button class="btn btn-info" onclick="resetStatistics()">
                    <i class="bi bi-arrow-clockwise"></i> 重置统计信息
                </button>
                <button class="btn btn-secondary" onclick="debugTaskStatus()">
                    <i class="bi bi-bug"></i> 调试状态
                </button>
            </div>
        </div>
        
        <!-- 任务统计 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body text-center">
                        <h4 id="totalTasks">0</h4>
                        <p class="mb-0">总任务数</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body text-center">
                        <h4 id="pendingTasks">0</h4>
                        <p class="mb-0">待执行</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body text-center">
                        <h4 id="runningTasks">0</h4>
                        <p class="mb-0">执行中</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body text-center">
                        <h4 id="successTasks">0</h4>
                        <p class="mb-0">已完成</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 任务列表 -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-table"></i> 任务列表</h5>
                <div class="btn-group" role="group">
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="loadTasks()">全部</button>
                    <button type="button" class="btn btn-outline-warning btn-sm" onclick="loadTasksByStatus('PENDING')">待执行</button>
                    <button type="button" class="btn btn-outline-info btn-sm" onclick="loadTasksByStatus('RUNNING')">执行中</button>
                    <button type="button" class="btn btn-outline-success btn-sm" onclick="loadTasksByStatus('SUCCESS')">已完成</button>
                </div>
            </div>
            <div class="card-body">
                <div id="tasksList">
                    <p class="text-center text-muted">加载中...</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 创建任务模态框 -->
    <div class="modal fade" id="createTaskModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-plus-circle"></i> 创建新任务</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="createTaskForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="taskName" class="form-label">任务名称 *</label>
                                    <input type="text" class="form-control" id="taskName" name="taskName" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="taskType" class="form-label">任务类型 *</label>
                                    <select class="form-select" id="taskType" name="taskType" required>
                                        <option value="">请选择任务类型</option>
                                        <option value="EMAIL">邮件发送</option>
                                        <option value="SMS">短信发送</option>
                                        <option value="NOTIFICATION">通知推送</option>
                                        <option value="DATA_PROCESSING">数据处理</option>
                                        <option value="REPORT_GENERATION">报告生成</option>
                                        <option value="CUSTOM">自定义任务</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="taskData" class="form-label">任务数据 (JSON格式)</label>
                            <textarea class="form-control" id="taskData" name="taskData" rows="3" placeholder='{"key": "value"}'></textarea>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="taskMode" class="form-label">任务模式</label>
                                    <select class="form-select" id="taskMode" name="taskMode" onchange="toggleTimeInput()">
                                        <option value="delay">延迟执行</option>
                                        <option value="scheduled">定时执行</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3" id="delayInput">
                                    <label for="delayMillis" class="form-label">延迟时间 (毫秒)</label>
                                    <input type="number" class="form-control" id="delayMillis" name="delayMillis" value="5000" min="1000">
                                </div>
                                <div class="mb-3" id="scheduledInput" style="display: none;">
                                    <label for="executeTime" class="form-label">执行时间</label>
                                    <input type="datetime-local" class="form-control" id="executeTime" name="executeTime">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="maxRetryCount" class="form-label">最大重试次数</label>
                                    <input type="number" class="form-control" id="maxRetryCount" name="maxRetryCount" value="3" min="0" max="10">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="retryInterval" class="form-label">重试间隔 (毫秒)</label>
                                    <input type="number" class="form-control" id="retryInterval" name="retryInterval" value="5000" min="1000">
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="priority" class="form-label">优先级</label>
                            <select class="form-select" id="priority" name="priority">
                                <option value="3">低</option>
                                <option value="0" selected>普通</option>
                                <option value="1">高</option>
                                <option value="2">紧急</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="createTask()">创建任务</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 任务详情模态框 -->
    <div class="modal fade" id="taskDetailModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-info-circle"></i> 任务详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="taskDetailContent">
                    <!-- 任务详情内容 -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="/js/utils.js"></script>
    <script>
        let currentTasks = [];
        let currentFilter = 'all';

        // 显示创建任务模态框
        function showCreateModal() {
            const modal = new bootstrap.Modal(document.getElementById('createTaskModal'));
            modal.show();
        }

        // 切换时间输入模式
        function toggleTimeInput() {
            const mode = document.getElementById('taskMode').value;
            const delayInput = document.getElementById('delayInput');
            const scheduledInput = document.getElementById('scheduledInput');
            
            if (mode === 'delay') {
                delayInput.style.display = 'block';
                scheduledInput.style.display = 'none';
            } else {
                delayInput.style.display = 'none';
                scheduledInput.style.display = 'block';
                
                // 设置默认时间为1小时后
                const now = new Date();
                now.setHours(now.getHours() + 1);
                document.getElementById('executeTime').value = now.toISOString().slice(0, 16);
            }
        }

        // 创建任务
        function createTask() {
            const form = document.getElementById('createTaskForm');
            const formData = new FormData(form);
            
            // 验证必填字段
            if (!formData.get('taskName') || !formData.get('taskType')) {
                showError('请填写必填字段');
                return;
            }
            
            // 构建请求数据
            const requestData = {
                taskName: formData.get('taskName'),
                taskType: formData.get('taskType'),
                taskData: formData.get('taskData') || '{}',
                maxRetryCount: parseInt(formData.get('maxRetryCount')),
                retryInterval: parseInt(formData.get('retryInterval')),
                priority: parseInt(formData.get('priority')) // 确保优先级是数字
            };
            
            // 根据模式设置时间参数
            if (formData.get('taskMode') === 'delay') {
                requestData.delayMillis = parseInt(formData.get('delayMillis'));
            } else {
                requestData.executeTime = formData.get('executeTime');
            }
            
            // 发送创建请求
            fetch('/api/tasks', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess('任务创建成功！');
                    bootstrap.Modal.getInstance(document.getElementById('createTaskModal')).hide();
                    form.reset();
                    loadTasks();
                    updateTaskStats();
                } else {
                    showError('创建失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('创建失败，请检查网络连接');
            });
        }

        // 加载任务列表
        function loadTasks() {
            currentFilter = 'all';
            fetch('/api/tasks')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    currentTasks = data.data;
                    renderTasks(data.data);
                } else {
                    showError('加载任务失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('加载任务失败，请检查网络连接');
            });
        }

        // 根据状态加载任务
        function loadTasksByStatus(status) {
            currentFilter = status;
            fetch(`/api/tasks/status/${status}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    currentTasks = data.data;
                    renderTasks(data.data);
                } else {
                    showError('加载任务失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('加载任务失败，请检查网络连接');
            });
        }

        // 渲染任务列表
        function renderTasks(tasks) {
            const container = document.getElementById('tasksList');
            if (!tasks || tasks.length === 0) {
                container.innerHTML = '<p class="text-center text-muted"><i class="bi bi-inbox"></i> 暂无任务</p>';
                return;
            }

            const html = `
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>任务ID</th>
                                <th>任务名称</th>
                                <th>类型</th>
                                <th>状态</th>
                                <th>优先级</th>
                                <th>执行时间</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${tasks.map(task => `
                                <tr>
                                    <td><code>${task.taskId.substring(0, 8)}...</code></td>
                                    <td>${task.taskName}</td>
                                    <td><span class="badge bg-secondary">${task.taskType}</span></td>
                                    <td>${getStatusBadge(task.status)}</td>
                                    <td>${getPriorityBadge(task.priority)}</td>
                                    <td>${formatDateTime(task.executeTime)}</td>
                                    <td>${formatDateTime(task.createTime)}</td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <button class="btn btn-outline-primary" onclick="viewTask('${task.taskId}')" title="查看详情">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                            ${task.status === 'PENDING' ? `
                                                <button class="btn btn-outline-danger" onclick="cancelTask('${task.taskId}')" title="取消任务">
                                                    <i class="bi bi-x-circle"></i>
                                                </button>
                                            ` : ''}
                                        </div>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
            container.innerHTML = html;
        }

        // 查看任务详情
        function viewTask(taskId) {
            fetch(`/api/tasks/${taskId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const task = data.data;
                    const content = document.getElementById('taskDetailContent');
                    content.innerHTML = `
                        <div class="row">
                            <div class="col-md-6">
                                <h6>基本信息</h6>
                                <table class="table table-sm">
                                    <tr><td>任务ID:</td><td><code>${task.taskId}</code></td></tr>
                                    <tr><td>任务名称:</td><td>${task.taskName}</td></tr>
                                    <tr><td>任务类型:</td><td><span class="badge bg-secondary">${task.taskType}</span></td></tr>
                                    <tr><td>状态:</td><td>${getStatusBadge(task.status)}</td></tr>
                                    <tr><td>优先级:</td><td>${getPriorityBadge(task.priority)}</td></tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <h6>时间信息</h6>
                                <table class="table table-sm">
                                    <tr><td>创建时间:</td><td>${formatDateTime(task.createTime)}</td></tr>
                                    <tr><td>执行时间:</td><td>${formatDateTime(task.executeTime)}</td></tr>
                                    <tr><td>开始时间:</td><td>${formatDateTime(task.startTime)}</td></tr>
                                    <tr><td>完成时间:</td><td>${formatDateTime(task.completeTime)}</td></tr>
                                </table>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-12">
                                <h6>任务数据</h6>
                                <pre class="bg-light p-2 rounded">${JSON.stringify(JSON.parse(task.taskData || '{}'), null, 2)}</pre>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <h6>重试信息</h6>
                                <table class="table table-sm">
                                    <tr><td>当前重试次数:</td><td>${task.currentRetryCount || 0}</td></tr>
                                    <tr><td>最大重试次数:</td><td>${task.maxRetryCount || 0}</td></tr>
                                    <tr><td>重试间隔:</td><td>${task.retryInterval || 0}ms</td></tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <h6>执行结果</h6>
                                <table class="table table-sm">
                                    <tr><td>错误信息:</td><td>${task.errorMessage || '-'}</td></tr>
                                    <tr><td>执行结果:</td><td>${task.result || '-'}</td></tr>
                                </table>
                            </div>
                        </div>
                    `;
                    
                    const modal = new bootstrap.Modal(document.getElementById('taskDetailModal'));
                    modal.show();
                } else {
                    showError('获取任务详情失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('获取任务详情失败，请检查网络连接');
            });
        }

        // 取消任务
        function cancelTask(taskId) {
            if (!confirm('确定要取消这个任务吗？')) {
                return;
            }
            
            fetch(`/api/tasks/${taskId}/cancel`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess('任务取消成功！');
                    loadTasks();
                    updateTaskStats();
                } else {
                    showError('取消失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('取消失败，请检查网络连接');
            });
        }

        // 清理已完成任务
        function cleanupCompletedTasks() {
            // 使用通用清理函数，清理1小时前的任务
            if (typeof window.globalCleanupCompletedTasks === 'function') {
                window.globalCleanupCompletedTasks(1, function(data) {
                    // 成功回调：刷新任务列表和统计
                    loadTasks();
                    updateTaskStats();
                }, function(errorMessage) {
                    // 错误回调：可以在这里添加额外的错误处理
                    console.error('清理任务失败:', errorMessage);
                });
            } else {
                // 如果通用函数不可用，使用备用实现
                cleanupCompletedTasksLocal();
            }
        }

        // 本地清理任务实现（避免递归调用）
        function cleanupCompletedTasksLocal() {
            if (!confirm('确定要清理所有已完成任务吗？此操作不可逆。')) {
                return;
            }
            
            // 设置清理时间为1小时前，使用本地时间
            const now = new Date();
            const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
            
            // 格式化为 YYYY-MM-DDTHH:mm:ss 格式，使用本地时间
            const year = oneHourAgo.getFullYear();
            const month = String(oneHourAgo.getMonth() + 1).padStart(2, '0');
            const day = String(oneHourAgo.getDate()).padStart(2, '0');
            const hours = String(oneHourAgo.getHours()).padStart(2, '0');
            const minutes = String(oneHourAgo.getMinutes()).padStart(2, '0');
            const seconds = String(oneHourAgo.getSeconds()).padStart(2, '0');
            
            const beforeTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
            
            console.log('清理时间参数:', {
                now: now.toLocaleString('zh-CN'),
                oneHourAgo: oneHourAgo.toLocaleString('zh-CN'),
                beforeTime: beforeTime
            });
            
            fetch(`/api/tasks/cleanup?beforeTime=${beforeTime}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess(`已完成任务清理成功！共清理 ${data.data} 个任务`);
                    loadTasks();
                    updateTaskStats();
                } else {
                    showError('清理失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('清理失败，请检查网络连接');
            });
        }

        // 重置统计信息
        function resetStatistics() {
            if (!confirm('确定要重置所有统计信息吗？此操作不可逆。')) {
                return;
            }
            fetch('/api/tasks/scheduler/statistics/reset', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess('统计信息已重置！');
                    updateTaskStats();
                } else {
                    showError('重置失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('重置失败，请检查网络连接');
            });
        }

        // 调试任务状态
        function debugTaskStatus() {
            fetch('/api/tasks')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const tasks = data.data;
                    const statusCounts = {};
                    const timeInfo = [];
                    
                    // 统计各状态的任务数量
                    tasks.forEach(task => {
                        statusCounts[task.status] = (statusCounts[task.status] || 0) + 1;
                        
                        // 收集时间信息
                        if (task.updateTime) {
                            timeInfo.push({
                                taskId: task.taskId.substring(0, 8),
                                status: task.status,
                                updateTime: task.updateTime,
                                createTime: task.createTime
                            });
                        }
                    });
                    
                    // 显示调试信息
                    let debugInfo = '任务状态分布:\n';
                    Object.entries(statusCounts).forEach(([status, count]) => {
                        debugInfo += `${status}: ${count}个\n`;
                    });
                    
                    debugInfo += '\n时间信息:\n';
                    timeInfo.slice(0, 10).forEach(info => {
                        debugInfo += `${info.taskId} - ${info.status} - 更新: ${info.updateTime} - 创建: ${info.createTime}\n`;
                    });
                    
                    if (timeInfo.length > 10) {
                        debugInfo += `... 还有 ${timeInfo.length - 10} 个任务\n`;
                    }
                    
                    console.log('Debug Info:', debugInfo);
                    alert(debugInfo);
                } else {
                    showError('获取调试信息失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('获取调试信息失败，请检查网络连接');
            });
        }

        // 更新任务统计
        function updateTaskStats() {
            fetch('/api/tasks')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const tasks = data.data;
                    document.getElementById('totalTasks').textContent = tasks.length;
                    document.getElementById('pendingTasks').textContent = tasks.filter(t => t.status === 'PENDING').length;
                    document.getElementById('runningTasks').textContent = tasks.filter(t => t.status === 'RUNNING').length;
                    document.getElementById('successTasks').textContent = tasks.filter(t => t.status === 'SUCCESS').length;
                }
            })
            .catch(error => {
                console.error('Error updating task stats:', error);
            });
        }

        // 获取状态徽章
        function getStatusBadge(status) {
            const statusMap = {
                'PENDING': { class: 'bg-warning', text: '待执行' },
                'RUNNING': { class: 'bg-info', text: '执行中' },
                'SUCCESS': { class: 'bg-success', text: '成功' },
                'FAILED': { class: 'bg-danger', text: '失败' },
                'CANCELLED': { class: 'bg-secondary', text: '已取消' },
                'RETRYING': { class: 'bg-warning', text: '重试中' },
                'TIMEOUT': { class: 'bg-danger', text: '超时' }
            };
            const statusInfo = statusMap[status] || { class: 'bg-secondary', text: status };
            return `<span class="badge ${statusInfo.class}">${statusInfo.text}</span>`;
        }

        // 获取优先级徽章
        function getPriorityBadge(priority) {
            const priorityMap = {
                0: { class: 'bg-primary', text: '普通' },
                1: { class: 'bg-warning', text: '高' },
                2: { class: 'bg-danger', text: '紧急' },
                3: { class: 'bg-secondary', text: '低' }
            };
            const priorityInfo = priorityMap[priority] || { class: 'bg-secondary', text: '未知' };
            return `<span class="badge ${priorityInfo.class}">${priorityInfo.text}</span>`;
        }

        // 格式化日期时间
        function formatDateTime(dateTimeStr) {
            if (!dateTimeStr) return '-';
            const date = new Date(dateTimeStr);
            return date.toLocaleString('zh-CN');
        }

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            loadTasks();
            updateTaskStats();
            
            // 每30秒刷新一次数据
            setInterval(() => {
                if (currentFilter === 'all') {
                    loadTasks();
                } else {
                    loadTasksByStatus(currentFilter);
                }
                updateTaskStats();
            }, 30000);
        });
    </script>
</body>
</html>
